import pandas as pd
import requests
import os
from .config import *

class MyDataIntegrityOrActivities():
    def __init__(self):
        pass

    def data_integrity(self, data: pd.DataFrame):

        flag1 = False
        flag2 = False
        flag3 = False
        flag4 = False
        # givenIngredient_set = set(data["givenIngredient"].keys())
        feedbackIngredient_set = set(data["feedbackIngredient"].keys())
        materialAnalysis_set = set(data["materialAnalysis"].keys())
        gypRatio_set = set(data["gypRatio"].keys())

        materialList_set = set(data["materialList"])

        material_merge_set = feedbackIngredient_set # & givenIngredient_set
        materialAnalysis_merge_set = materialAnalysis_set & (gypRatio_set | material_merge_set)

        # 1 反馈，物料化学分析 数据对其过滤
        # if (len(material_merge_set) == (len(materialList_set)-len(gypRatio_set)+1)) & (len(materialAnalysis_merge_set) == (len(materialList_set))):
        flag1 = True
        # 2 过程质量列缺失过滤
        processQuality_set = set(data["processQuality"].keys())
        if "CaO" in processQuality_set:
            current_set = {'细度45μm', 'Loss', 'CaO', '比表', 'SO3'}
            if len(current_set - processQuality_set) == 0:
                flag2 = True
        else:
            current_set = {'细度45μm', 'Loss', '混合材总掺量', '石灰石掺量', '比表', 'SO3'}
            if len(current_set - processQuality_set) == 0:
                flag2 = True

        # 3 石灰石Loss过滤
        if (data["materialAnalysis"]['石灰石']['Loss'] is not None) & (data["materialAnalysis"]['石灰石']['Loss'] != 0):
            flag3 = True
        # 4 熟料掺比过滤
        if 60<data["feedbackIngredient"]["熟料"]<90:
            flag4 = True

        return flag1 & flag2 & flag3 &flag4

    def data_filter(self, data_in: pd.DataFrame):
        
        self.data = data_in
        # 空值过滤
        # self.data = self.data[self.data["gypRatio"].notna() & (self.data["gypRatio"]!={})]
        # self.data = self.data[self.data["givenIngredient"].notna() & (self.data["givenIngredient"]!={})]
        self.data = self.data[self.data["feedbackIngredient"].notna() & (self.data["feedbackIngredient"]!={})]
        self.data = self.data[self.data["materialAnalysis"].notna() & (self.data["materialAnalysis"]!={})]
        self.data = self.data[self.data["processQuality"].notna() & (self.data["processQuality"]!={})]

        self.data = self.data[self.data["clinkerStrengthPrediction3d"].notna() & self.data["clinkerStrengthPrediction28d"].notna() & self.data["checkStrength1d"].notna()]
        self.data = self.data[(self.data["clinkerStrengthPrediction3d"] > 0) & (self.data["clinkerStrengthPrediction28d"] > 0) & (self.data["checkStrength1d"] > 0)]

        for i in self.data.index:
            if self.data_integrity(self.data.loc[i]) == False:
                # print(self.data.loc[i])
                self.data = self.data.drop(i, axis=0)
        self.materialAnalysis_avg()
        return self.data
    

    def materialAnalysis_avg(self):
        # LOGGER.info('计算各种物料的平均值......')
        data = pd.DataFrame(list(self.data['materialAnalysis']))
        self.material_chemical = {}
        for col in data.columns:
            data_children = list(data[col][data[col].notna()])
            data_children = pd.DataFrame(data_children)
            self.material_chemical[col] = data_children.mean().to_dict()
    def get_activities(self, material_type_in_train):

        if 'KUBERNETES_SERVICE_HOST' in os.environ:
            url = "http://machine-learning:8080/api/v1/model/api/invoke"
        else:
            url = basis_config["host_get_static"]


        chemical_dict = {name:self.material_chemical[name] for name in material_type_in_train}

        data_input= {'modelCode': 'cement_batching_general_model', 'params': {}}
        data_input["params"]["cement_type"] = "po425"
        data_input["params"]["细度45μm"] = {}
        data_input["params"]["比表"] = {}
        data_input["params"]["SO3"] = {}
        data_input["params"].update(chemical_dict)
        # print(data_input)
        print("通用模型输入：", data_input)
        print("通用模型url: ",url)
        header = {'Content-Type': 'application/json;charset=UTF-8', 'current_tenant_id': "1"}
        data_output = requests.post(url, json=data_input, headers=header).json()
        print("通用模型输出为：",data_output)
        if data_output["status"] == "success":
            print("********通用模型返回结果：***********\n",data_output)
            self.activities = {name: data_output["data"][name]["activity"] for name in material_type_in_train}
        else:
            raise ValueError("调用通用模型失败")
        
        return self.activities 